export default class TopMarker {
  constructor(chart) {
    this.chart = chart // 图表实例
    this.point = this.getMaxPoint() // 该频标在实时线上的基准点
    this.chart.topMarker = this
    this.index = '峰值'
    this.marker = null // 标记点renderer定义 svg > path
    this.drawCustomShape()
    this.visible = true
  }
  getMaxPoint() {
    const points = this.getPoints(this.chart.series[0])
    let max = points[0]
    for (let i = 0; i < points.length; i++) {
      const y = points[i].y
      if (!max || y > max.y) {
        max = points[i]
      }
    }
    return max
  }
  drawCustomShape() {
    if (this.marker) {
      this.marker.destroy()
    }
    const renderer = this.chart.renderer
    const x = this.point.plotX + this.chart.plotLeft
    const y = this.chart.plotSizeY + this.chart.plotTop + 30
    var path = [] // 添加路径
    path.push('M', x - 8, y) // 移动到起始点
    path.push('L', x + 8, y) // 画一条线
    path.push('L', x + 8, y - 20) // 画一条线
    path.push('L', x, y - 30) // 画一条线
    path.push('L', x - 8, y - 20) // 画一条线
    path.push('Z') // 关闭路径  // 将路径添加到图表中
    path.push('M', x, y - 30)
    path.push('L', x, this.chart.plotTop)
    const strokeColor = '#f3f3f3'
    const fillColor = 'rgba(243, 243, 243, 0.3)'
    this.marker = renderer
      .path(path)
      .attr({ stroke: strokeColor, 'stroke-width': 1, fill: fillColor, zIndex: 2 })
    this.marker.add()
  }
  getPoints(item) {
    const { points, data, xData, yData } = item
    if (points.length > 0) {
      return points
    } else if (data.length > 0) {
      return data
    } else {
      return xData.map((x, i) => [x, yData[i]])
    }
  }
  update() {
    this.point = this.getMaxPoint()
    this.visible && this.drawCustomShape()
  }
  setVisible(val) {
    this.visible = val
    if (val) {
      this.marker.show()
    } else {
      this.marker.hide()
    }
  }
}
